﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using ConexionAgente;

namespace Manager
{
    class ServerController
    {
        private const int MAX_CANT_SERV = 5;
        private Thread[] serverThreads = new Thread[5];
        private Object mutex = null;

        public ServerController()
        {
        }

        public void IniciarServicio(Object mutex)
        {
            this.mutex = mutex;
            Thread th = new Thread(InterrogarServidores);
            th.Start();
        }

        private void InterrogarServidores()
        {
            try
            {

                while (true)
                {
                    Thread.Sleep(1000); // Duerme un segundo

                    Console.WriteLine("Interrogando Servidores...");
                    int count = 0;
                    foreach (ServerNode s in Manager.conf.ObtenerServidores())
                    {
                        serverThreads[count] = new Thread(InterrogarServidor);
                        serverThreads[count].Start(s);
                        count++;
                    }
                    if (serverThreads[0] != null) serverThreads[0].Join();
                    if (serverThreads[1] != null) serverThreads[1].Join();
                    if (serverThreads[2] != null) serverThreads[2].Join();
                    if (serverThreads[3] != null) serverThreads[3].Join();
                    if (serverThreads[4] != null) serverThreads[4].Join();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
        }
        
        private void InterrogarServidor(object objServidor)
        {
            ServerNode srv = (ServerNode)objServidor;
            lock (this.mutex)
            {
                srv.actualizarDatos();
            }
        }

    }

}
